package com.qsmx.qingqiuticket.app.delegate.group;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateGroupBuyBinding;
import com.qsmx.qingqiuticket.app.entity.GoodsInfoEntity;
import com.qsmx.qingqiuticket.app.entity.GroupPackageListEntity;
import com.qsmx.qingqiuticket.app.event.QrScanEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;

public class GroupBuyDelegate extends AtmosDelegate {
    private AppCompatTextView tvErrorTips;
    private CountDownTimerUtil timer;
    private Dialog inputDialog;
    private DelegateGroupBuyBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_group_buy;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        startCountDownTime(60);
        SoundPlayUtils.play(2);

        mBinding = DelegateGroupBuyBinding.bind(rootView);

        mBinding.tvInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    showInputDialog();
                }
            }
        });

        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSupportDelegate().pop();
                }
            }
        });
    }

    private void showInputDialog() {
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        if (timer != null) {
            timer.cancel();
        }
        inputDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        inputDialog.setCancelable(true);
        inputDialog.show();
        Window window = inputDialog.getWindow();
        window.setContentView(R.layout.dialog_input_code);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        int height = (int) (DimenUtil.getScreenHeight() * 0.7);

        window.setLayout(width, height);

        AppCompatTextView tvNum1 = window.findViewById(R.id.tv_num_1);
        AppCompatTextView tvNum2 = window.findViewById(R.id.tv_num_2);
        AppCompatTextView tvNum3 = window.findViewById(R.id.tv_num_3);
        AppCompatTextView tvNum4 = window.findViewById(R.id.tv_num_4);
        AppCompatTextView tvNum5 = window.findViewById(R.id.tv_num_5);
        AppCompatTextView tvNum6 = window.findViewById(R.id.tv_num_6);
        AppCompatTextView tvNum7 = window.findViewById(R.id.tv_num_7);
        AppCompatTextView tvNum8 = window.findViewById(R.id.tv_num_8);
        AppCompatTextView tvNum9 = window.findViewById(R.id.tv_num_9);
        AppCompatTextView tvNum0 = window.findViewById(R.id.tv_num_0);
        AppCompatTextView tvClean = window.findViewById(R.id.tv_clean);
        AppCompatTextView tvBack = window.findViewById(R.id.tv_back);
        AppCompatTextView tvScan = window.findViewById(R.id.tv_scan);
        AppCompatEditText tvGoodsId = window.findViewById(R.id.tv_goods_id);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        ClickUtil.disableShowSoftInput(tvGoodsId);

        tvErrorTips = window.findViewById(R.id.tv_error_tips);

        tvNum1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("1", tvGoodsId);
            }
        });

        tvNum2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("2", tvGoodsId);
            }
        });

        tvNum3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("3", tvGoodsId);
            }
        });

        tvNum4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("4", tvGoodsId);
            }
        });

        tvNum5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("5", tvGoodsId);
            }
        });

        tvNum6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("6", tvGoodsId);
            }
        });

        tvNum7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("7", tvGoodsId);
            }
        });

        tvNum8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("8", tvGoodsId);
            }
        });

        tvNum9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("9", tvGoodsId);
            }
        });

        tvNum0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appendOneNum("0", tvGoodsId);
            }
        });

        tvClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearNums(tvGoodsId);
            }
        });

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteOneNum(tvGoodsId);
            }
        });

        tvScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkGroupInfo(tvGoodsId.getText().toString());
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputDialog.dismiss();
            }
        });

        inputDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                startCountDownTime(60);
            }
        });

        inputDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        });

        inputDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        });

    }

    private void appendOneNum(String num, AppCompatEditText tvGoodsId) {
        tvGoodsId.setText(tvGoodsId.getText().toString() + num);
        tvGoodsId.setSelection(tvGoodsId.getText().length());
    }

    private void clearNums(AppCompatEditText tvGoodsId) {
        tvGoodsId.setText("");
        tvGoodsId.setSelection(tvGoodsId.getText().length());
    }

    private void deleteOneNum(AppCompatEditText tvGoodsId) {
        String phoneStr = tvGoodsId.getText().toString();
        if (!StringUtil.isEmpty(phoneStr)) {
            tvGoodsId.setText(phoneStr.substring(0, phoneStr.length() - 1));
            tvGoodsId.setSelection(tvGoodsId.getText().length());
        }
    }

    private void startCountDownTime(final long time) {
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvTime.setText(String.format(getString(R.string.back_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                getSupportDelegate().pop();
            }
        };
        timer.start();// 开始计时
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (isVisible()) {
            if (event != null && event.getData() != null) {
                String qrCode = event.getData().getString(FusionTag.QR_CODE);
                //todo 查询会员卡
//            checkCard("", qrCode);
//            onPayOrder(qrCode);
                checkGroupInfo(qrCode);
            }
        }
    }

    private void checkGroupInfo(String verifiedCode) {
        DialogUtil.showLoadingDialog(getContext(), "正在查询订单...");
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;

        JSONObject params = new JSONObject();
        params.put("verifiedCode", verifiedCode);
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));

        HttpHelper.RestClientPostRaw(params, HttpUrl.GROUP_VERIFIED_QUERY,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<GroupPackageListEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            GroupPackageListEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (inputDialog != null && inputDialog.isShowing()) {
                                    inputDialog.dismiss();
                                }
                                getSupportDelegate().start(GroupPackageDelegate.create(mData, verifiedCode));
                            } else {
                                if (inputDialog != null && inputDialog.isShowing()) {
                                    tvErrorTips.setText(mData.getHeader().getMessage());
                                } else {
                                    DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                                }
                                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                                FusionCode.QrIsLoading = false;
                            }
                        } catch (Exception e) {
                            if (inputDialog != null && inputDialog.isShowing()) {
                                tvErrorTips.setText(getString(R.string.service_error));
                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), e.getMessage(), "确定");
                            }
                            FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                            FusionCode.QrIsLoading = false;
                        }

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        if (inputDialog != null && inputDialog.isShowing()) {
                            tvErrorTips.setText(msg);
                        } else {
                            DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                        }
                        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                        FusionCode.QrIsLoading = false;
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        if (inputDialog != null && inputDialog.isShowing()) {
                            tvErrorTips.setText("网络错误");
                        } else {
                            DialogUtil.showCardErrorDialog(getContext(), "网络错误", "确定");
                        }
                        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                        FusionCode.QrIsLoading = false;
                    }
                });
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (AtmosPreference.getCustomStringPre(FusionPre.HOME_TYPE).equals("2") || AtmosPreference.getCustomStringPre(FusionPre.HOME_TYPE).equals("3")) {
            startCountDownTime(60);
        }

        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
        FusionCode.QrIsLoading = false;
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (timer != null) {
            timer.cancel();
        }
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtil.dismissErrorDialog();
        EventBus.getDefault().unregister(this);
        FusionData.mMemData = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
